﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enter.DataProxy.Cache.Configuration;
using System.Web;
using Enter.Common;
using System.Collections;
using Enter.Common.Helper;

namespace Enter.DataProxy.Cache
{
    internal sealed class WebCache : ICacheService
    {
        private static System.Web.Caching.Cache cache;
        private static int _DEFAULT_MINUTES = 10;
        private static bool _enableCache = false;
        private static string _CacheName = string.Empty;
        private static bool _enableLog = false;

        public WebCache()
        {
            GetCurrentCache();
            if (_enableCache)
            {
                //CheckError();
            }
        }

        public void GetCurrentCache()
        {
            CacheConfigurationManager MemManager = new CacheConfigurationManager();
            CacheSetting MemcachedSetting = MemManager.GetMemSetting();
            _enableCache = MemcachedSetting.EnableCaching;
            if (_enableCache)
            {
                cache = HttpRuntime.Cache;
            }
        }


        public bool IsCache()
        {
            return _enableCache;
            //throw new NotImplementedException();
        }

        public void ReleaseConnection()
        {
            cache = HttpRuntime.Cache;
            //throw new NotImplementedException();
        }

        public void DeltelCache()
        {
            if (cache.Count > 0)
            {
                foreach (DictionaryEntry entry in cache)
                {
                    cache.Remove(entry.Key.ToString());
                }
            }
        }

        public T Get<T>(string key)
        {
            return GetValue<T>(GetKeyStr(key));

            //throw new NotImplementedException();
        }


        public List<T> GetObjectsByKey<T>(List<string> key)
        {
            return null;
        }


        public Dictionary<string, T> GetKeyObjectsByKey<T>(List<string> key)
        {
            return null;
            //throw new NotImplementedException();
        }


        public void Remove(string key)
        {
            cache.Remove(key);
        }

        public void Remove(List<string> key)
        {
            if ((key != null) && (key.Count > 0))
            {
                foreach (string k in key)
                {
                    Remove(k);
                }
            }
        }


        public void Put(string key, object value)
        {
            Put(key, value, _DEFAULT_MINUTES);
        }


        public void Put(string key, object value, int Seconds)
        {
            if (value != null)
            {
                if (_enableCache)
                {
                    SaveValue(key,value,Seconds);
                   
                }
            }
        }


        public bool Exists(string key)
        {
            if (_enableCache)
            {
                object obj = cache.Get(GetKeyStr(key));
                if (obj != null)
                {
                    return true;
                }
                return false;
            }
            else
            {
                return false;
            }
        }

        #region 私有方法

        /// <summary>
        /// 转化Key为MemCache实际存储的KEY
        /// </summary>
        /// <param name="key">KEY</param>
        /// <param name="region">区域</param>
        /// <returns></returns>
        private string GetKeyStr(string key)
        {
            string result = string.Format("[{0}]{1}", _CacheName, key);
            return result;

        }

        private string RemoveKeyStr(string key)
        {
            string result = key.Replace(string.Format("[{0}]", _CacheName), "");
            return result;
        }

        private string GetDeltelCacheName()
        {
            string result = string.Format("[{0}]", _CacheName);
            return result;
        }



        /// <summary>
        /// 保存数据到缓存服务器
        /// </summary>
        /// <param name="key">处理过的KEY</param>
        /// <param name="value">值</param>
        /// <param name="Seconds">保存时间</param>
        /// <param name="region">区域</param>
        private void SaveValue(string key, object value, int Seconds)
        {
            if (_enableCache)
            {
                if (Seconds == 0)
                {
                    Seconds = _DEFAULT_MINUTES;
                }
                DateTime timespan = DateTime.Now.AddSeconds(Seconds);

                string values = CacheCommon.ObjToString(value);

                cache.Insert(GetKeyStr(key), values, null, timespan, TimeSpan.Zero);

                //cache.Set(key, values, timespan);
            }
        }

        /// <summary>
        /// 从缓存服务器得到值
        /// </summary>
        /// <typeparam name="T">值</typeparam>
        /// <param name="key">处理过的KEY</param>
        /// <returns></returns>
        private T GetValue<T>(string key)
        {
            object obj = GetObjValue(key);
            if (obj != null)
            {
                if (_enableLog)
                {
                    LogHelper.LogInfo(string.Format("★Key:{0} 找到缓存", key));
                }
                return CacheCommon.StringToObj<T>(obj.ToString());
            }
            else
            {
                if (_enableLog)
                {
                    if (_enableCache)
                    {
                        LogHelper.LogInfo(string.Format("☆Key:{0} 未找到缓存", key));
                    }
                }
                //return null;
                return default(T);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private object GetObjValue(string key)
        {
            if (_enableCache)
            {
                return cache.Get(key);
            }
            else
            {
                return null;
            }
        }



        #endregion

    }
}
